#include "Sock.hpp"
#include <sys/epoll.h>

const int NUM = 1024;

int main()
{
    // 创建epoll句柄
    int epfd = epoll_create(NUM);
    // 构建epoll事件
    struct epoll_event event;
    event.events = EPOLLIN; // 设置读事件
    event.data.fd = 0;
    // 添加关心事件
    epoll_ctl(epfd, EPOLL_CTL_ADD, 0, &event);
    // 等待事件
    struct epoll_event revent;
    // int timeout = 5000; // ms
    // int timeout = -1;
    int timeout = 0;

    while (true)
    {
        int ret = epoll_wait(epfd, &revent, 1, timeout);

        switch (ret)
        {
        case -1:
            fprintf(stderr, "Wait: %s\n", strerror(errno));
            break;
        case 0:
            fprintf(stdout, "timeout!\n");
            sleep(2);
            break;
        default:
            // std::cout << "ret: " << ret << std::endl; // 返回值是就绪事件数量
            for (int i = 0; i < ret; ++i)
            {
                char buffer[NUM];
                ssize_t s = read(event.data.fd, buffer, sizeof(buffer) - 1); // 当作字符串
                switch (s)
                {
                case -1:
                    fprintf(stderr, "Read: %s\n", strerror(errno));
                    break;
                case 0:
                    fprintf(stdout, "对端关闭连接!\n");
                    break;
                default:
                    buffer[s - 1] = '\0';
                    // fprintf(stdout, "client[%d]# %s\n", buffer);
                    if (write(1, buffer, s) == -1)
                    {
                        fprintf(stderr, "Write: %s\n", strerror(errno));
                        exit(6);
                    }
                }
            }
        }
    }

    close(epfd);
    return 0;
}

// void Usage(std::string proc)
// {
//     std::cout << "Usage: " << proc << " port" << std::endl;
// }

// // ./epoll_server port
// int main(int argc, char* argv[])
// {
//     if(argc != 2)
//     {
//         Usage(argv[0]);
//         exit(1);
//     }

//     int listen_sockfd = Sock::Socket();
//     Sock::Bind(listen_sockfd, static_cast<uint16_t>(atoi(argv[1])));
//     Sock::Listen(listen_sockfd);
//     // int fd = Sock::Accept(listen_sockfd);

//     //close(fd);
//     close(listen_sockfd);
//     return 0;
// }